package com.wanmait.wanmarecruit.webController;

import com.alibaba.fastjson.JSONObject;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
public class SendCodeController {

    //初始化--榛子云
    private String apiUrl = "https://sms_developer.zhenzikj.com";
    private String appId = "112304";
    private String appSecret = "360de19c-530b-436b-aaad-94e5431e94d9";

    //获得存在session里的短信验证码，并返回到jsp页面验证码
    @RequestMapping("/getCode")
    @ResponseBody
    public String getCode(HttpSession session){
        return ((JSONObject)session.getAttribute("code")).getString("code");
    }

    @RequestMapping("/sendCode")
    @ResponseBody
    public boolean getCode(String memPhone, HttpSession httpSession){
        try {
            JSONObject json = null;
            //生成6位验证码
            String code = String.valueOf(new Random().nextInt(899999)+100000);
            //将验证码通过榛子云接口发送至手机（关键）
            ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
            Map<String, Object> params = new HashMap<String, Object>();
            //页面输入的手机号
            params.put("number", memPhone);
            //模板ID
            params.put("templateId", 10314);
            String[] templateParams = new String[2];
            templateParams[0] = code;
            //有效时间
            templateParams[1] = "5分钟";
            params.put("templateParams", templateParams);
            String result = client.send(params);
            json = JSONObject.parseObject(result);
            //code不为0，短信发送失败
            if (json.getIntValue("code")!=0){
                return  false;
            }
            //将验证码存到session中,同时存入创建时间
            json = new JSONObject();
            //手机号
            json.put("memPhone",memPhone);
            //6位验证码
            json.put("code",code);
            //创建时间
            json.put("createTime",System.currentTimeMillis());
            //将验证码存入session
            httpSession.setAttribute("code",json);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
